package com.wdh.kjs.activity;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.wdh.kjs.Adapter.IM_investrecord_Adapter;
import com.wdh.kjs.R;
import com.wdh.kjs.http.Httpurl;
import com.wdh.kjs.http.response.MyCookieStore;
import com.wdh.kjs.model.JsonModel;
import com.wdh.kjs.model.JsonModel_my;
import com.wdh.kjs.util.ToastUtils;

import org.apache.http.impl.client.DefaultHttpClient;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Locale;

/**
 * Created by CQH on 2016/4/21.
 */
public class CompletedTransferActivity extends BaseTopActivity implements View.OnClickListener{
    private String orderId;
    private String partyId;
    private ImageView upload_portrait;
    private String upOrDown = "";
    private LinearLayout ll_pc_take_photo, ll_pc_pick_photo, ll_pc_cancel;
    private PopupWindow popwindow;
    private ImageView iv_voucher;
    private TextView tv_activity_ct;
    private Button bt_activity_ct_push;
    private JsonModel_my jsonModel_my;

    private static final int MY_PERMISSIONS_REQUEST_STORAGE_CODE = 17;
    private static final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 27;
    private String fileDir = "/sdcard/kjs2/";
    private String voucherUrl = "";
    private File tempFile = null;
    private Bitmap bitmap;
    private Uri pictureUri = null;
    private String zhanghu;
    private String mima;
    private JsonModel jsonModel;
    private SharedPreferences sharedPreferences;
    ProgressDialog m_pDialog;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_completed_transfer);
        orderId = getIntent().getStringExtra("id");

        m_pDialog = new ProgressDialog(CompletedTransferActivity.this);
        m_pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        m_pDialog.setIcon(R.drawable.logo);
        m_pDialog.setTitle("温馨提示");
        m_pDialog.setMessage("不要着急，图片正在上传中哦~~~");
        m_pDialog.setCancelable(true);

        sharedPreferences =getSharedPreferences("logininfo", MODE_PRIVATE);
        partyId = sharedPreferences.getString("loginToken", "");
        zhanghu = sharedPreferences.getString("zhanghao", "");
        mima = sharedPreferences.getString("mima", "");
        initTopBar("确认完成转账");
        denglu();
        upload_portrait = (ImageView) findViewById(R.id.upload_portrait);
        iv_voucher = (ImageView) findViewById(R.id.iv_activity_ct);
        tv_activity_ct = (TextView) findViewById(R.id.tv_activity_ct);
        bt_activity_ct_push = (Button) findViewById(R.id.bt_activity_ct_push);
        bt_activity_ct_push.setOnClickListener(this);
        upload_portrait.setOnClickListener(this);

    }


        private void denglu() {
            RequestParams params = new RequestParams();
            params.addBodyParameter("USERNAME", zhanghu);
            params.addBodyParameter("PASSWORD", mima);
            final HttpUtils http = new HttpUtils();
            http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_LOGIN, params, new RequestCallBack<String>() {

                @Override
                public void onSuccess(ResponseInfo<String> responseInfo) {

                    Gson gson = new Gson();
                    jsonModel = gson.fromJson(responseInfo.result, JsonModel.class);
                    String m = jsonModel.getPartyId();
                    if (jsonModel._LOGIN_PASSED_()) {
                        DefaultHttpClient zpf = (DefaultHttpClient) http.getHttpClient();
                        MyCookieStore.firstCookieStore = zpf.getCookieStore();
                        SharedPreferences.Editor editor = getSharedPreferences("logininfo", MODE_PRIVATE).edit();
                        editor.putString("loginToken", jsonModel.getPartyId());
                        editor.putString("nickName", jsonModel.getNickName());
                        editor.putString("phoneNumber", jsonModel.getPhoneNumber());
                        editor.putString("levels", jsonModel.getLevels());
                        editor.putString("type", jsonModel.getType());
                        editor.putString("zhanghao", zhanghu);
                        editor.putString("mima", mima);
                        editor.commit();
                    }


                }

                @Override
                public void onFailure(HttpException error, String msg) {


                }
            });

        }

    private void initweb() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("partyId", partyId);
        params.addBodyParameter("orderId", orderId);
        params.addBodyParameter("uploadedFile", tempFile);

        HttpUtils http = new HttpUtils();
        http.configCookieStore(MyCookieStore.firstCookieStore);

        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_PUSH_PINGZHENG, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Gson gson = new Gson();
                jsonModel_my = gson.fromJson(responseInfo.result, JsonModel_my.class);
                if (jsonModel_my.success) {
                    m_pDialog.dismiss();
                    ToastUtils.showShort(CompletedTransferActivity.this, jsonModel_my.getMsg());
                    startActivity(new Intent(CompletedTransferActivity.this,InvestManageActivity2.class));
                }
                else
                    ToastUtils.showShort(CompletedTransferActivity.this, jsonModel_my.getMsg());
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                ToastUtils.showShort(CompletedTransferActivity.this, "网络异常！");
            }
        });

    }

    public void onClick(View v){
        switch (v.getId()) {
            case R.id.upload_portrait:
                tv_activity_ct.setVisibility(View.GONE);
                iv_voucher.setVisibility(View.VISIBLE);
                upOrDown = "up";
                InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm.isActive()) {
                    imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);

                }
                showPopWindow();
                darken();
                break;
            case R.id.bt_activity_ct_push:
                m_pDialog.show();
                        initweb();
        }
        }
    private void showPopWindow() {
        //ToastUtils.showShort(this, "popwindow");
        final View contentView = LayoutInflater.from(this).inflate(
                R.layout.view_picture_choose, null);
//        ll_pc_take_photo = (LinearLayout) contentView.findViewById(R.id.ll_pc_take_photo);
        ll_pc_pick_photo = (LinearLayout) contentView.findViewById(R.id.ll_pc_pick_photo);
        ll_pc_cancel = (LinearLayout) contentView.findViewById(R.id.ll_pc_cancel);
//        ll_pc_take_photo.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (ContextCompat.checkSelfPermission(CompletedTransferActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
//                    ActivityCompat.requestPermissions(CompletedTransferActivity.this,
//                            new String[]{Manifest.permission.CAMERA},
//                            MY_PERMISSIONS_REQUEST_STORAGE_CODE);
//                }else {
//                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//
//                boolean canUse = true;
//                android.hardware.Camera mCamera = null;
//                try {
//                    mCamera = android.hardware.Camera.open(0);
//                    mCamera.setDisplayOrientation(90);
//                } catch (Exception e) {
//                    canUse = false;
//                }
//                if (canUse) {
//                    mCamera.release();
//                    mCamera = null;
//                    startActivityForResult(intent, 0);
//                    Log.e("ChainWinFinance", "摄像头已打开");
//                } else {
//
//                    ToastUtils.showShort(CompletedTransferActivity.this, "请先打开摄像头权限1111111！");
//                }
//                }
//            }
//        }
//        );
        ll_pc_pick_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

//                if (ContextCompat.checkSelfPermission(CompletedTransferActivity.this,
//                        Manifest.permission.READ_CONTACTS)
//                        != PackageManager.PERMISSION_GRANTED) {
//                    ActivityCompat.requestPermissions(CompletedTransferActivity.this,
//                            new String[]{Manifest.permission.READ_CONTACTS},
//                            MY_PERMISSIONS_REQUEST_READ_CONTACTS);
//                }else{
//                    //
//                }
                if (ContextCompat.checkSelfPermission(CompletedTransferActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(CompletedTransferActivity.this,
                            new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                            MY_PERMISSIONS_REQUEST_READ_CONTACTS);
                }else {
                Intent intent = new Intent(
                        Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, 1);
                }
            }
        });
        ll_pc_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popwindow.dismiss();
            }
        });

        popwindow = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        popwindow.setAnimationStyle(R.style.anim_popup_dir);
        popwindow.setTouchable(true);
        popwindow.setFocusable(true);
        popwindow.setBackgroundDrawable(new BitmapDrawable());
        popwindow.setOutsideTouchable(true);
        popwindow.setOnDismissListener(new poponDismissListener());
        //Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL---屏幕中间
        popwindow.showAtLocation(findViewById(R.id.upload_portrait), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
        contentView.setOnTouchListener(new View.OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event) {

                int height = contentView.findViewById(R.id.ll_popup).getTop();
                int y = (int) event.getY();
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    if (y < height) {
                        brighten();
                        popwindow.dismiss();
                    }
                }
                return true;
            }
        });

    }
    class poponDismissListener implements PopupWindow.OnDismissListener {

        @Override
        public void onDismiss() {
            // TODO Auto-generated method stub
            //Log.v("List_noteTypeActivity:", "我是关闭事件");
            brighten();
        }

    }

    private void darken() {
        WindowManager.LayoutParams lp =getWindow().getAttributes();
        lp.alpha = 0.7f; //0.0-1.0
        getWindow().setAttributes(lp);
    }

    private void brighten() {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 1.0f; //0.0-1.0
        getWindow().setAttributes(lp);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (popwindow != null && popwindow.isShowing()) {
            popwindow.dismiss();
        }

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 0) {
                String sdStatus = Environment.getExternalStorageState();
                if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
                    Log.i("TestFile",
                            "SD card is not avaiable/writeable right now.");
                    return;
                }
                String name = new DateFormat().format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
//                Toast.makeText(CompletedTransferActivity.this, name, Toast.LENGTH_LONG).show();
                Bundle bundle = data.getExtras();
                Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式

                FileOutputStream b = null;
                //???????????????????????????????为什么不能直接保存在系统相册位置呢？？？？？？？？？？？？
                File file = new File(fileDir);
                file.mkdirs();// 创建文件夹
                String fileName = fileDir + name;

                try {
                    b = new FileOutputStream(fileName);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        b.flush();
                        b.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

//                Uri uri = Uri.parse(fileName);
//                for (int i = 0; i < SelectPictureUrl.getSelectPicture().size(); i++)
//                    SelectPictureUrl.getSelectPicture().remove(i);
//                SelectPictureUrl.getSelectPicture().add(fileName);
                voucherUrl = fileName;
//                iv_voucher.setImageURI(uri);
//                tempFile = new File(fileName);

                File picture = new File(fileName);
                String absolutePath = picture.getAbsolutePath();
                String time = new DateFormat().format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + "";
                String filePath = picture.getParent() + "/" + "pick" + time + absolutePath.substring(absolutePath.lastIndexOf("."));
                Log.e("ChainWinFinance", "DDDfilePath" + filePath);
                tempFile = new File(filePath);
                try {
                    tempFile.createNewFile();//必须要执行
                } catch (IOException e) {
                    e.printStackTrace();
                }

                copyfile(picture, tempFile, true);

                if (tempFile.exists()) {

                    try {

                        if (iv_voucher != null && iv_voucher.getDrawable() != null) {

                            Bitmap oldBitmap = ((BitmapDrawable) iv_voucher.getDrawable()).getBitmap();

                            iv_voucher.setImageDrawable(null);

                            if (oldBitmap != null) {

                                oldBitmap.recycle();
                                Log.e("ChainWinFinance", "内存回收！");
                                oldBitmap = null;

                            }

                        }
                        FileInputStream stream = new FileInputStream(tempFile);
                        BitmapFactory.Options opts = new BitmapFactory.Options();
                        opts.inJustDecodeBounds = true;
                        BitmapFactory.decodeFile(filePath, opts);
                        opts.inSampleSize = computeSampleSize(opts, -1, 130 * 130);
                        opts.inJustDecodeBounds = false;
                        Bitmap btp = BitmapFactory.decodeStream(stream, null, opts);
                        iv_voucher.setImageBitmap(btp);
                        long size = tempFile.length(); // 大小 bytes
                        long temp = 1024 * 1024 * 2;
                        int inSampleSize = 1;
                        if (size > temp) {
                            Log.e("ChainWinFinance", "上传压缩");
                            long i = size / temp;
                            inSampleSize = getInSampleSize(i);
                            bitmap = getBitmap(tempFile, filePath, inSampleSize);
                            saveBitmapFile(bitmap, tempFile);
                            Log.e("ChainWinFinance", "inSampleSize:" + inSampleSize);
                            Log.e("ChainWinFinance", "tempFile.length()压缩后:" + tempFile.length() / (1024 * 1024));
                        }
                        Log.e("ChainWinFinance", "上传图片大小" + tempFile.length());
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }

                } else
                    ToastUtils.showShort(CompletedTransferActivity.this, "文件不存在！");
            } else if (requestCode == 1) {
                if (data != null) {
                    Uri uri = data.getData();
                    String fileType = uri.getScheme();
                    if (!fileType.equals("file")) {
                        if (iv_voucher != null && iv_voucher.getDrawable() != null) {

                            Bitmap oldBitmap = ((BitmapDrawable) iv_voucher.getDrawable()).getBitmap();

                            iv_voucher.setImageDrawable(null);

                            if (oldBitmap != null) {

                                oldBitmap.recycle();
                                Log.e("ChainWinFinance", "内存回收！");
                                oldBitmap = null;

                            }

                        }
                        String path;
                        if (!android.text.TextUtils.isEmpty(uri.getAuthority())) {
                            Cursor cursor = CompletedTransferActivity.this.getContentResolver().query(uri,
                                    new String[]{MediaStore.Images.Media.DATA}, null, null, null);
                            if (null == cursor) {
                                Toast.makeText(CompletedTransferActivity.this, "图片没找到", Toast.LENGTH_SHORT).show();
                                return;
                            }
                            cursor.moveToFirst();
                            path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                            cursor.close();
                        } else {
                            path = uri.getPath();
                        }
//                    iv_voucher.setImageURI(Uri.parse(path));
                        File picture = new File(path);
                        String filename = picture.getAbsolutePath();
                        String name = new DateFormat().format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + "";
                        String filePath = picture.getParent() + "/" + name + filename.substring(filename.lastIndexOf("."));
                        tempFile = new File(filePath);
                        try {
                            tempFile.createNewFile();//必须要执行
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        copyfile(picture, tempFile, true);

                        if (tempFile.exists()) {
                            try {
//                                ToastUtils.showShort(CompletedTransferActivity.this, "已选择图片：" + path);
                                FileInputStream stream = new FileInputStream(tempFile);
                                BitmapFactory.Options opts = new BitmapFactory.Options();
                                opts.inJustDecodeBounds = true;
                                BitmapFactory.decodeFile(filePath, opts);
                                opts.inSampleSize = computeSampleSize(opts, -1, 130 * 130);
                                opts.inJustDecodeBounds = false;
                                Bitmap btp = BitmapFactory.decodeStream(stream, null, opts);
                                Log.e("ChainWinFinance", "inSampleSize:" + opts.inSampleSize);
                                iv_voucher.setImageBitmap(btp);
                                long size = tempFile.length(); // 大小 bytes
                                long temp = 1024 * 1024 * 2;
                                int inSampleSize = 1;
                                if (size > temp) {
                                    Log.e("ChainWinFinance", "上传压缩");
                                    long i = size / temp;
                                    inSampleSize = getInSampleSize(i);
//                                    inSampleSize = (int) ((int) size % temp == 0 ? size / temp : size / temp + 1);
//                                    int inSampleSize = (int) (size / temp);
//                                    if (inSampleSize < 2)
//                                        inSampleSize = 2;
                                    bitmap = getBitmap(tempFile, filePath, inSampleSize);
                                    saveBitmapFile(bitmap, tempFile);
                                    Log.e("ChainWinFinance", "inSampleSize:" + inSampleSize);
                                    Log.e("ChainWinFinance", "tempFile.length()压缩后:" + tempFile.length() / (1024 * 1024));
                                }
                                pictureUri = uri;
                                Log.e("ChainWinFinance", "上传图片大小" + tempFile.length());
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }

                        } else
                            ToastUtils.showShort(CompletedTransferActivity.this, "文件不存在！");
                    } else
                        ToastUtils.showShort(CompletedTransferActivity.this, "不能上传云上的图片，请选择本地图片！");


                } else {
                    Toast.makeText(CompletedTransferActivity.this, "图片没找到", Toast.LENGTH_SHORT).show();
                    return;
                }

            }

        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    public static int computeSampleSize(BitmapFactory.Options options,

                                        int minSideLength, int maxNumOfPixels) {

        int initialSize = computeInitialSampleSize(options, minSideLength,

                maxNumOfPixels);


        int roundedSize;

        if (initialSize <= 8) {

            roundedSize = 1;

            while (roundedSize < initialSize) {

                roundedSize <<= 1;

            }

        } else {

            roundedSize = (initialSize + 7) / 8 * 8;

        }


        return roundedSize;
    }
    private static int computeInitialSampleSize(BitmapFactory.Options options,

                                                int minSideLength, int maxNumOfPixels) {

        double w = options.outWidth;

        double h = options.outHeight;


        int lowerBound = (maxNumOfPixels == -1) ? 1 :

                (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));

        int upperBound = (minSideLength == -1) ? 128 :

                (int) Math.min(Math.floor(w / minSideLength),

                        Math.floor(h / minSideLength));


        if (upperBound < lowerBound) {

            // return the larger one when there is no overlapping zone.

            return lowerBound;

        }


        if ((maxNumOfPixels == -1) &&

                (minSideLength == -1)) {

            return 1;

        } else if (minSideLength == -1) {

            return lowerBound;

        } else {

            return upperBound;

        }
    }
    private int getInSampleSize(long i) {
        int inSampleSize = 1;
        if (0 < i && i <= 4)
            inSampleSize = 2;
        else if (4 < i && i <= 16)
            inSampleSize = 4;
        else if (16 < i && i <= 64)
            inSampleSize = 8;
        else if (64 < i && i <= 256)
            inSampleSize = 16;
        else if (256 < i && i <= 1024)
            inSampleSize = 32;
        return inSampleSize;
    }

    public void saveBitmapFile(Bitmap bitmap, File file) {
//        File file = new File(path);//将要保存图片的路径
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Bitmap getBitmap(File file, String path, int inSampleSize) {
        FileInputStream stream = null;
        try {
            stream = new FileInputStream(file);
            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(path, opts);
            opts.inSampleSize = inSampleSize;
            opts.inJustDecodeBounds = false;
            Bitmap btp = BitmapFactory.decodeStream(stream, null, opts);
            return btp;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void copyfile(File fromFile, File toFile, Boolean rewrite) {
        if (!fromFile.exists()) {
            return;
        }
        if (!fromFile.isFile()) {
            return;
        }
        if (!fromFile.canRead()) {
            return;
        }
        if (!toFile.getParentFile().exists()) {
            toFile.getParentFile().mkdirs();
        }
        if (toFile.exists() && rewrite) {
            toFile.delete();
        }
        //当文件不存时，canWrite一直返回的都是false
        // if (!toFile.canWrite()) {
        // MessageDialog.openError(new Shell(),"错误信息","不能够写将要复制的目标文件" + toFile.getPath());
        // Toast.makeText(this,"不能够写将要复制的目标文件", Toast.LENGTH_SHORT);
        // return ;
        // }
        try {
            java.io.FileInputStream fosfrom = new java.io.FileInputStream(fromFile);
            java.io.FileOutputStream fosto = new FileOutputStream(toFile);
            byte bt[] = new byte[1024];
            int c;
            while ((c = fosfrom.read(bt)) > 0) {
                fosto.write(bt, 0, c); //将内容写到新文件当中
            }
            fosfrom.close();
            fosto.close();
        } catch (Exception ex) {
            Log.e("readfile", ex.getMessage());
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
//            case MY_PERMISSIONS_REQUEST_STORAGE_CODE: {
//                // If request is cancelled, the result arrays are empty.
//                if (grantResults.length > 0
//                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//
//                boolean canUse = true;
//                android.hardware.Camera mCamera = null;
//                try {
//                    mCamera = android.hardware.Camera.open(0);
//                    mCamera.setDisplayOrientation(90);
//                } catch (Exception e) {
//                    canUse = false;
//                }
//                if (canUse) {
//                    mCamera.release();
//                    mCamera = null;
//                    startActivityForResult(intent, 0);
//                    Log.e("ChainWinFinance", "摄像头已打开");
//                } else {
//
//                    ToastUtils.showShort(CompletedTransferActivity.this, "请先打开摄像头权限！");
//                }
//                    // permission was granted, yay! Do the
//                    // contacts-related task you need to do.
//
//                } else {
//
//                    // permission denied, boo! Disable the
//                    // functionality that depends on this permission.
//                }
//
//            }
//            break;
            case MY_PERMISSIONS_REQUEST_READ_CONTACTS:

                if (grantResults.length>0 && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.
                    Intent intent = new Intent(
                            Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent, 1);
                } else {
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(CompletedTransferActivity.this, "权限错误，无法正常工作！", Toast.LENGTH_SHORT).show();
                }
                return;


        }

    }

}
